package com.psl.servlet;

import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@WebServlet(name = "DownloadServlet")
public class DownloadServlet
        extends HttpServlet {
    public static String filenameEncoding(String filename, HttpServletRequest request)
            throws IOException {
        String agent = request.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();

            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else if (agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String fileName = request.getParameter("fileName");
        String coding_fileName = filenameEncoding(fileName, request);
        String fileUUid = request.getParameter("fileUUid");
        String filetype = request.getParameter("filetype");
        String path = "C:\\webfile\\" + filetype;

        File file = new File(path + "\\" + fileUUid);
        if (file.exists()) {
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + coding_fileName + "\"");

            InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            byte[] bytes = new byte['?'];
            ServletOutputStream outStream = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(outStream);
            int readLength = 0;
            while ((readLength = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, readLength);
            }
            inputStream.close();
            bis.close();
            bos.flush();
            outStream.close();
            bos.close();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
